package com.test.practice.io.objectstream;

import lombok.Cleanup;

import java.io.*;

/**
 * 对象流
 *
 * @Description: 对象流
 * =======================
 * @Author: Jovi
 * =======================
 * @Date: Created in 2023-02-10
 * =======================
 * @Version: 1.1.2.0
 */
public class ObjectStreamDemo {

    public static void main(String[] args) throws Exception {
//        m1();

        m2();

        m3();
    }


    /**
     * 反序列化
     *
     * @throws Exception
     */
    private static void m3() throws Exception {
        @Cleanup FileInputStream fis = new FileInputStream("ttt.txt");
        @Cleanup ObjectInputStream ois = new ObjectInputStream(fis);

        Order o = (Order) ois.readObject();
        System.out.println(o);
    }

    /**
     * 序列化自定义类
     *
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private static void m2() throws Exception {
        @Cleanup FileOutputStream fos = new FileOutputStream("ttt.txt");
        @Cleanup ObjectOutputStream oos = new ObjectOutputStream(fos);


        Order order = new Order();
        order.setOrderId("你好");
//        order.setNum(123);

        oos.writeObject(order);
        oos.flush();

    }

    /**
     * 序列化字符串
     *
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private static void m1() throws IOException, ClassNotFoundException {
        @Cleanup FileOutputStream fos = new FileOutputStream("ttt.txt");
        @Cleanup ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject("你好");
        oos.flush();

        FileInputStream fis = new FileInputStream("ttt.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);

        Object o = ois.readObject();
        System.out.println(o);
    }

}
